package com.campus.util;

import com.campus.entity.Account;
import com.campus.mapper.AccountMapper;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


@Component
public class ElasticSearchUtils {

    private final int MAX_PAGE_SIZE = 50;

    @Resource
    private ElasticsearchRestTemplate template;

    @Autowired
    @Qualifier("accountMapper")
    private AccountMapper accountMapper;


    /**
     * 保存一个数据
     *
     * @param account
     * @return
     */
    public Account save(Account account) {
        return accountMapper.save(account);
    }

    public void delete(Account account) {
        accountMapper.deleteById(account.getAccountId());
    }

    public void delete(String id) {
        accountMapper.deleteById(id);
    }

    public SearchHits<Account> match(Account account) {

        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        //设置查询条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        for(String s:account.getLabel()){
            boolQuery.should(QueryBuilders.matchQuery("label",s));
        }
        boolQuery.minimumShouldMatch(1);

        boolQuery.mustNot(QueryBuilders.termQuery("accountId",account.getAccountId()));
        System.out.println(boolQuery);
        /**
         * 根据score排序
         */
        builder.withSorts(SortBuilders.scoreSort());

        builder.withPageable(PageRequest.of(0, MAX_PAGE_SIZE));
        builder.withQuery(boolQuery);
        /**
         * 查询
         */
        return template.search(builder.build(), Account.class);
    }

    public void update(Account account) {
        accountMapper.deleteById(account.getAccountId());
        accountMapper.save(account);
    }
}
